//! # 网关核心错误定义
//!
//! 定义网关系统的统一错误类型，提供一致的错误处理机制。

use axum::http::StatusCode;
use std::fmt;

/// 网关操作结果类型
pub type GatewayResult<T> = Result<T, GatewayError>;

/// 网关错误类型
#[derive(Debug, Clone)]
pub enum GatewayError {
    /// 认证错误
    Authentication {
        /// 错误消息
        message: String,
        /// 错误代码
        code: String,
    },
    /// 授权错误
    Authorization {
        /// 错误消息
        message: String,
        /// 缺少的权限
        required_permission: Option<String>,
    },
    /// 限流错误
    RateLimit {
        /// 错误消息
        message: String,
        /// 重试时间（秒）
        retry_after: Option<u64>,
        /// 限流规则ID
        rule_id: Option<String>,
    },
    /// 路由错误
    Routing {
        /// 错误消息
        message: String,
        /// 原始路径
        path: String,
    },
    /// 服务发现错误
    ServiceDiscovery {
        /// 错误消息
        message: String,
        /// 服务名称
        service_name: String,
    },
    /// 负载均衡错误
    LoadBalance {
        /// 错误消息
        message: String,
        /// 服务名称
        service_name: String,
    },
    /// 网络错误
    Network {
        /// 错误消息
        message: String,
        /// 错误类型
        error_type: NetworkErrorType,
    },
    /// 配置错误
    Configuration {
        /// 错误消息
        message: String,
        /// 配置项名称
        config_key: Option<String>,
    },
    /// 验证错误
    Validation {
        /// 错误消息
        message: String,
        /// 验证字段
        field: Option<String>,
    },
    /// 内部错误
    Internal {
        /// 错误消息
        message: String,
    },
    /// 超时错误
    Timeout {
        /// 错误消息
        message: String,
        /// 超时时间（毫秒）
        timeout_ms: u64,
    },
}

/// 网络错误类型
#[derive(Debug, Clone)]
pub enum NetworkErrorType {
    /// 连接错误
    Connection,
    /// DNS解析错误
    DnsResolution,
    /// 超时
    Timeout,
    /// 协议错误
    Protocol,
    /// 其他网络错误
    Other,
}

impl GatewayError {
    /// 创建认证错误
    pub fn authentication(message: impl Into<String>) -> Self {
        Self::Authentication {
            message: message.into(),
            code: "AUTH_FAILED".to_string(),
        }
    }

    /// 创建授权错误
    pub fn authorization(message: impl Into<String>) -> Self {
        Self::Authorization {
            message: message.into(),
            required_permission: None,
        }
    }

    /// 创建限流错误
    pub fn rate_limit(message: impl Into<String>) -> Self {
        Self::RateLimit {
            message: message.into(),
            retry_after: None,
            rule_id: None,
        }
    }

    /// 创建路由错误
    pub fn routing(message: impl Into<String>, path: impl Into<String>) -> Self {
        Self::Routing {
            message: message.into(),
            path: path.into(),
        }
    }

    /// 创建服务发现错误
    pub fn service_discovery(message: impl Into<String>, service_name: impl Into<String>) -> Self {
        Self::ServiceDiscovery {
            message: message.into(),
            service_name: service_name.into(),
        }
    }

    /// 创建负载均衡错误
    pub fn load_balance(message: impl Into<String>, service_name: impl Into<String>) -> Self {
        Self::LoadBalance {
            message: message.into(),
            service_name: service_name.into(),
        }
    }

    /// 创建网络错误
    pub fn network(message: impl Into<String>, error_type: NetworkErrorType) -> Self {
        Self::Network {
            message: message.into(),
            error_type,
        }
    }

    /// 创建配置错误
    pub fn configuration(message: impl Into<String>) -> Self {
        Self::Configuration {
            message: message.into(),
            config_key: None,
        }
    }

    /// 创建验证错误
    pub fn validation(message: impl Into<String>) -> Self {
        Self::Validation {
            message: message.into(),
            field: None,
        }
    }

    /// 创建内部错误
    pub fn internal(message: impl Into<String>) -> Self {
        Self::Internal {
            message: message.into(),
        }
    }

    /// 创建超时错误
    pub fn timeout(message: impl Into<String>, timeout_ms: u64) -> Self {
        Self::Timeout {
            message: message.into(),
            timeout_ms,
        }
    }

    /// 获取错误消息
    pub fn message(&self) -> &str {
        match self {
            Self::Authentication { message, .. } => message,
            Self::Authorization { message, .. } => message,
            Self::RateLimit { message, .. } => message,
            Self::Routing { message, .. } => message,
            Self::ServiceDiscovery { message, .. } => message,
            Self::LoadBalance { message, .. } => message,
            Self::Network { message, .. } => message,
            Self::Configuration { message, .. } => message,
            Self::Validation { message, .. } => message,
            Self::Internal { message } => message,
            Self::Timeout { message, .. } => message,
        }
    }

    /// 获取HTTP状态码
    pub fn status_code(&self) -> StatusCode {
        match self {
            Self::Authentication { .. } => StatusCode::UNAUTHORIZED,
            Self::Authorization { .. } => StatusCode::FORBIDDEN,
            Self::RateLimit { .. } => StatusCode::TOO_MANY_REQUESTS,
            Self::Routing { .. } => StatusCode::NOT_FOUND,
            Self::ServiceDiscovery { .. } => StatusCode::SERVICE_UNAVAILABLE,
            Self::LoadBalance { .. } => StatusCode::SERVICE_UNAVAILABLE,
            Self::Network { .. } => StatusCode::BAD_GATEWAY,
            Self::Configuration { .. } => StatusCode::INTERNAL_SERVER_ERROR,
            Self::Validation { .. } => StatusCode::BAD_REQUEST,
            Self::Internal { .. } => StatusCode::INTERNAL_SERVER_ERROR,
            Self::Timeout { .. } => StatusCode::GATEWAY_TIMEOUT,
        }
    }

    /// 获取错误代码
    pub fn error_code(&self) -> &str {
        match self {
            Self::Authentication { .. } => "GATEWAY_AUTH_ERROR",
            Self::Authorization { .. } => "GATEWAY_AUTHZ_ERROR",
            Self::RateLimit { .. } => "GATEWAY_RATE_LIMIT",
            Self::Routing { .. } => "GATEWAY_ROUTING_ERROR",
            Self::ServiceDiscovery { .. } => "GATEWAY_SERVICE_DISCOVERY_ERROR",
            Self::LoadBalance { .. } => "GATEWAY_LOAD_BALANCE_ERROR",
            Self::Network { .. } => "GATEWAY_NETWORK_ERROR",
            Self::Configuration { .. } => "GATEWAY_CONFIG_ERROR",
            Self::Validation { .. } => "GATEWAY_VALIDATION_ERROR",
            Self::Internal { .. } => "GATEWAY_INTERNAL_ERROR",
            Self::Timeout { .. } => "GATEWAY_TIMEOUT_ERROR",
        }
    }

    /// 是否为可重试错误
    pub fn is_retryable(&self) -> bool {
        matches!(
            self,
            Self::Network { .. } | Self::ServiceDiscovery { .. } | Self::LoadBalance { .. } | Self::Timeout { .. }
        )
    }
}

impl fmt::Display for GatewayError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.error_code(), self.message())
    }
}

impl std::error::Error for GatewayError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}

impl From<std::io::Error> for GatewayError {
    fn from(error: std::io::Error) -> Self {
        Self::network(format!("IO错误: {}", error), NetworkErrorType::Other)
    }
}

impl From<serde_json::Error> for GatewayError {
    fn from(error: serde_json::Error) -> Self {
        Self::validation(format!("JSON解析错误: {}", error))
    }
}

impl From<tokio::time::error::Elapsed> for GatewayError {
    fn from(error: tokio::time::error::Elapsed) -> Self {
        Self::timeout(format!("操作超时: {}", error), 30000)
    }
}